/**
  * Author: Mei
  * Date: 2020-12-13 15:11
  * Description:
  * 容器一般分为序列式、关联式、不定序的容器(Unordered Containers)底层是hashtable(11新加）
  *
  */
#include "../../head.h"

using namespace std;

#define Size 500000

long get_a_target_long() {
    long target = 0;
    cout << "target (0." << endl;
}

int compareLongs(const void *a, const void *b) {
    return (*(long *) a - *(long *) b);
}

int compareStrings(const void *a, const void *b) {
    if (*(string *) a > *(string *) b) {
        return 1;
    } else if (*(string *) a < *(string *) b) {
        return -1;
    } else {
        return 0;
    }
}

int main() {
    vector<string> vec;
    char buf[10];
    clock_t timeStart = clock();
    for (long i = 0; i < Size; ++i) {
        try {
            snprintf(buf, 10, "%d", rand());
            vec.push_back(string(buf));
        } catch (exception &p) {
            cout << "i=" << i << " " << p.what() << endl;
            abort(); //退出
        }
    }
    cout << "mill-seconds: " << (clock() - timeStart) << endl;
    cout << "array.size() = " << vec.size() << endl;
    cout << "array.front() = " << vec.front() << endl;
    cout << "array.back() = " << vec.back() << endl;
    cout << "array.data() = " << vec.data() << endl;
    cout << "array.capacity() = " << vec.capacity() << endl;
    //排序
    string target = "100";
    timeStart = clock();
    auto pItem = find(vec.begin(), vec.end(), target); //::全局函数
    cout << "find()--mill-seconds: " << (clock() - timeStart) << endl;
    if (pItem != vec.end()) {
        cout << "found." << *pItem << endl;
    } else {
        cout << "not found!" << endl;
    }

    {
        timeStart = clock();
        //排序
        sort(vec.begin(), vec.end());
        //查找之前需要有序
        string *pItem = (string *) bsearch(&target, (vec.data()), vec.size(), sizeof(string), compareStrings);
        cout << "sort()+bsearch()--mill-seconds: " << (clock() - timeStart) << endl;
        if (pItem != NULL) {
            cout << "found." << *pItem << endl;
        } else {
            cout << "not found!" << endl;
        }
    }

    /**
     * 执行结果
     *  mill-seconds: 135
        array.size() = 500000
        array.front() = 41
        array.back() = 29794
        array.data() = 0x3563040
        array.capacity() = 524288 有空间的浪费
        find()--mill-seconds: 1
        found.100
        sort()+bsearch()--mill-seconds: 1509  //主要花在排序上面
        found.100

     *
     */
    return 0;
}